/**
 * 信访分析系统 - 经纬度分析模块
 * 负责地理信息分析、地图可视化、空间统计分析等功能
 */

class CoordinateAnalysisManager {
    constructor() {
        this.init();
        this.bindEvents();
        this.map = null;
        this.markers = [];
        this.heatmap = null;
        this.pollutionChart = null;
        this.trendChart = null;
        this.analysisMode = 'heatmap';
        this.filters = new Map();
    }

    /**
     * 初始化模块
     */
    init() {
        console.log('经纬度分析模块初始化完成');
        this.loadMap();
        this.initCharts();
        this.loadStatistics();
    }

    /**
     * 绑定事件监听器
     */
    bindEvents() {
        // 分析模式切换
        this.bindAnalysisModeChange();
        
        // 查询和重置按钮
        this.bindSearchAndReset();
        
        // 地图控制按钮
        this.bindMapControls();
        
        // 图表交互
        this.bindChartInteractions();
        
        // 数据导出
        this.bindDataExport();
    }

    /**
     * 加载地图
     */
    loadMap() {
        // 模拟地图加载
        setTimeout(() => {
            this.initializeMap();
        }, 1000);
    }

    /**
     * 初始化地图
     */
    initializeMap() {
        const mapContainer = document.getElementById('map');
        if (mapContainer) {
            // 清除加载提示
            mapContainer.innerHTML = '';
            
            // 模拟Leaflet地图初始化
            this.createMockMap();
            
            // 加载地理数据
            this.loadGeoData();
        }
    }

    /**
     * 创建模拟地图
     */
    createMockMap() {
        const mapContainer = document.getElementById('map');
        mapContainer.innerHTML = `
            <div class="relative w-full h-full bg-slate-50 rounded-lg overflow-hidden">
                <div class="absolute inset-0 bg-gradient-to-br from-blue-50 to-green-50">
                    <!-- 模拟地图网格 -->
                    <div class="absolute inset-0 opacity-20">
                        <div class="grid grid-cols-8 grid-rows-6 h-full w-full">
                            ${Array(48).fill(0).map(() => '<div class="border border-slate-300"></div>').join('')}
                        </div>
                    </div>
                    
                    <!-- 模拟地图标记 -->
                    <div class="absolute top-1/4 left-1/3 w-4 h-4 bg-red-500 rounded-full border-2 border-white shadow-lg cursor-pointer hover:scale-125 transition-transform" title="南山区科技园"></div>
                    <div class="absolute top-1/3 left-1/2 w-4 h-4 bg-orange-500 rounded-full border-2 border-white shadow-lg cursor-pointer hover:scale-125 transition-transform" title="福田区中心区"></div>
                    <div class="absolute top-1/2 left-2/3 w-4 h-4 bg-yellow-500 rounded-full border-2 border-white shadow-lg cursor-pointer hover:scale-125 transition-transform" title="宝安国际机场"></div>
                    <div class="absolute top-2/3 left-1/4 w-4 h-4 bg-green-500 rounded-full border-2 border-white shadow-lg cursor-pointer hover:scale-125 transition-transform" title="罗湖区东门"></div>
                    <div class="absolute top-3/4 left-3/4 w-4 h-4 bg-blue-500 rounded-full border-2 border-white shadow-lg cursor-pointer hover:scale-125 transition-transform" title="龙岗区坂田"></div>
                    
                    <!-- 模拟热力图效果 -->
                    <div class="absolute top-1/4 left-1/3 w-32 h-32 bg-red-200 rounded-full opacity-30 blur-xl"></div>
                    <div class="absolute top-1/3 left-1/2 w-24 h-24 bg-orange-200 rounded-full opacity-30 blur-xl"></div>
                    <div class="absolute top-1/2 left-2/3 w-20 h-20 bg-yellow-200 rounded-full opacity-30 blur-xl"></div>
                    
                    <!-- 地图控制按钮 -->
                    <div class="absolute top-4 right-4 flex flex-col space-y-2">
                        <button class="w-10 h-10 bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow flex items-center justify-center">
                            <i class="fas fa-plus text-slate-600"></i>
                        </button>
                        <button class="w-10 h-10 bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow flex items-center justify-center">
                            <i class="fas fa-minus text-slate-600"></i>
                        </button>
                        <button class="w-10 h-10 bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow flex items-center justify-center">
                            <i class="fas fa-home text-slate-600"></i>
                        </button>
                    </div>
                    
                    <!-- 图例 -->
                    <div class="absolute bottom-4 left-4 bg-white rounded-lg shadow-lg p-3">
                        <h4 class="text-sm font-semibold text-slate-800 mb-2">污染等级</h4>
                        <div class="space-y-1">
                            <div class="flex items-center space-x-2">
                                <div class="w-4 h-4 bg-red-500 rounded-full"></div>
                                <span class="text-xs text-slate-600">高风险</span>
                            </div>
                            <div class="flex items-center space-x-2">
                                <div class="w-4 h-4 bg-yellow-500 rounded-full"></div>
                                <span class="text-xs text-slate-600">中风险</span>
                            </div>
                            <div class="flex items-center space-x-2">
                                <div class="w-4 h-4 bg-green-500 rounded-full"></div>
                                <span class="text-xs text-slate-600">低风险</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 绑定地图标记点击事件
        this.bindMarkerEvents();
    }

    /**
     * 绑定地图标记事件
     */
    bindMarkerEvents() {
        const markers = document.querySelectorAll('#map .rounded-full.cursor-pointer');
        markers.forEach(marker => {
            marker.addEventListener('click', (e) => {
                const title = e.target.getAttribute('title');
                this.showLocationDetail(title);
            });
        });
    }

    /**
     * 显示位置详情
     */
    showLocationDetail(location) {
        console.log('显示位置详情:', location);
        this.showNotification(`正在查看 ${location} 的详细信息...`, 'info');
    }

    /**
     * 加载地理数据
     */
    loadGeoData() {
        console.log('加载地理数据...');
        
        // 模拟地理数据
        const geoData = [
            { lat: 22.5455, lng: 113.9308, location: '南山区科技园', count: 45, type: 'air', risk: 'high' },
            { lat: 22.5329, lng: 114.0579, location: '福田区中心区', count: 38, type: 'noise', risk: 'medium' },
            { lat: 22.6393, lng: 113.8111, location: '宝安国际机场', count: 32, type: 'noise', risk: 'medium' },
            { lat: 22.5431, lng: 114.1297, location: '罗湖区东门', count: 28, type: 'environment', risk: 'low' },
            { lat: 22.6056, lng: 114.0649, location: '龙岗区坂田', count: 25, type: 'soil', risk: 'medium' }
        ];
        
        this.updateMapMarkers(geoData);
    }

    /**
     * 更新地图标记
     */
    updateMapMarkers(data) {
        console.log('更新地图标记:', data);
        // 这里应该根据分析模式更新地图显示
        this.updateAnalysisDisplay();
    }

    /**
     * 初始化图表
     */
    initCharts() {
        this.initPollutionChart();
        this.initTrendChart();
    }

    /**
     * 初始化污染类型分布图表
     */
    initPollutionChart() {
        const canvas = document.getElementById('pollutionChart');
        if (canvas) {
            const ctx = canvas.getContext('2d');
            
            // 模拟Chart.js饼图
            this.pollutionChart = this.createMockPieChart(ctx, {
                labels: ['空气污染', '噪音污染', '水污染', '土壤污染', '市容管理'],
                data: [35, 25, 20, 12, 8],
                colors: ['#ef4444', '#f97316', '#3b82f6', '#eab308', '#8b5cf6']
            });
        }
    }

    /**
     * 初始化时间趋势图表
     */
    initTrendChart() {
        const canvas = document.getElementById('trendChart');
        if (canvas) {
            const ctx = canvas.getContext('2d');
            
            // 模拟Chart.js折线图
            this.trendChart = this.createMockLineChart(ctx, {
                labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
                data: [120, 135, 98, 156, 178, 145]
            });
        }
    }

    /**
     * 创建模拟饼图
     */
    createMockPieChart(ctx, config) {
        const centerX = ctx.canvas.width / 2;
        const centerY = ctx.canvas.height / 2;
        const radius = Math.min(centerX, centerY) - 20;
        
        let currentAngle = 0;
        const total = config.data.reduce((sum, value) => sum + value, 0);
        
        config.data.forEach((value, index) => {
            const sliceAngle = (value / total) * 2 * Math.PI;
            
            // 绘制扇形
            ctx.beginPath();
            ctx.moveTo(centerX, centerY);
            ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle);
            ctx.closePath();
            ctx.fillStyle = config.colors[index];
            ctx.fill();
            
            // 绘制标签
            const labelAngle = currentAngle + sliceAngle / 2;
            const labelX = centerX + Math.cos(labelAngle) * (radius + 15);
            const labelY = centerY + Math.sin(labelAngle) * (radius + 15);
            
            ctx.fillStyle = '#374151';
            ctx.font = '10px sans-serif';
            ctx.textAlign = 'center';
            ctx.fillText(config.labels[index], labelX, labelY);
            
            currentAngle += sliceAngle;
        });
        
        return { ctx, config };
    }

    /**
     * 创建模拟折线图
     */
    createMockLineChart(ctx, config) {
        const padding = 20;
        const chartWidth = ctx.canvas.width - 2 * padding;
        const chartHeight = ctx.canvas.height - 2 * padding;
        
        // 清空画布
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        
        // 绘制坐标轴
        ctx.strokeStyle = '#e5e7eb';
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(padding, padding);
        ctx.lineTo(padding, ctx.canvas.height - padding);
        ctx.lineTo(ctx.canvas.width - padding, ctx.canvas.height - padding);
        ctx.stroke();
        
        // 绘制数据线
        const maxValue = Math.max(...config.data);
        const xStep = chartWidth / (config.labels.length - 1);
        const yScale = chartHeight / maxValue;
        
        ctx.strokeStyle = '#3b82f6';
        ctx.lineWidth = 2;
        ctx.beginPath();
        
        config.data.forEach((value, index) => {
            const x = padding + index * xStep;
            const y = ctx.canvas.height - padding - (value * yScale);
            
            if (index === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        });
        
        ctx.stroke();
        
        // 绘制数据点
        config.data.forEach((value, index) => {
            const x = padding + index * xStep;
            const y = ctx.canvas.height - padding - (value * yScale);
            
            ctx.fillStyle = '#3b82f6';
            ctx.beginPath();
            ctx.arc(x, y, 3, 0, 2 * Math.PI);
            ctx.fill();
        });
        
        return { ctx, config };
    }

    /**
     * 加载统计数据
     */
    loadStatistics() {
        console.log('加载统计数据...');
        
        // 模拟统计数据更新
        this.updateStatisticsDisplay();
    }

    /**
     * 更新统计显示
     */
    updateStatisticsDisplay() {
        // 这里可以更新统计卡片的数据
        console.log('更新统计显示');
    }

    /**
     * 绑定分析模式切换
     */
    bindAnalysisModeChange() {
        const analysisMode = document.querySelector('select[placeholder*="分析模式"]');
        if (analysisMode) {
            analysisMode.addEventListener('change', (e) => {
                this.analysisMode = e.target.value;
                this.updateAnalysisDisplay();
            });
        }
    }

    /**
     * 绑定搜索和重置按钮
     */
    bindSearchAndReset() {
        const searchBtn = document.querySelector('button:has(.fa-search)');
        const resetBtn = document.querySelector('button:has(.fa-redo)');
        
        if (searchBtn) {
            searchBtn.addEventListener('click', () => {
                this.performSearch();
            });
        }
        
        if (resetBtn) {
            resetBtn.addEventListener('click', () => {
                this.resetFilters();
            });
        }
    }

    /**
     * 绑定地图控制按钮
     */
    bindMapControls() {
        // 图层按钮
        const layerBtn = document.querySelector('button:has(.fa-layer-group)');
        if (layerBtn) {
            layerBtn.addEventListener('click', () => {
                this.showLayerControl();
            });
        }
        
        // 全屏按钮
        const fullscreenBtn = document.querySelector('button:has(.fa-expand)');
        if (fullscreenBtn) {
            fullscreenBtn.addEventListener('click', () => {
                this.toggleFullscreen();
            });
        }
    }

    /**
     * 绑定图表交互
     */
    bindChartInteractions() {
        // 污染类型图表点击事件
        const pollutionCanvas = document.getElementById('pollutionChart');
        if (pollutionCanvas) {
            pollutionCanvas.addEventListener('click', (e) => {
                this.handleChartClick(e, 'pollution');
            });
        }
        
        // 趋势图表点击事件
        const trendCanvas = document.getElementById('trendChart');
        if (trendCanvas) {
            trendCanvas.addEventListener('click', (e) => {
                this.handleChartClick(e, 'trend');
            });
        }
    }

    /**
     * 绑定数据导出
     */
    bindDataExport() {
        const exportBtn = document.querySelector('button:has(.fa-download)');
        if (exportBtn) {
            exportBtn.addEventListener('click', () => {
                this.exportGeoData();
            });
        }
    }

    /**
     * 执行搜索
     */
    performSearch() {
        console.log('执行地理数据搜索...');
        
        // 收集筛选条件
        const filters = {
            region: document.querySelector('select[placeholder*="区县"]')?.value,
            pollutionType: document.querySelector('select[placeholder*="污染类型"]')?.value,
            timeRange: document.querySelector('select[placeholder*="时间范围"]')?.value,
            keyword: document.querySelector('input[placeholder*="搜索地址"]')?.value
        };
        
        console.log('搜索条件:', filters);
        
        // 模拟搜索过程
        this.showNotification('正在搜索...', 'info');
        
        setTimeout(() => {
            this.updateSearchResults(filters);
            this.showNotification('搜索完成', 'success');
        }, 1000);
    }

    /**
     * 更新搜索结果
     */
    updateSearchResults(filters) {
        console.log('更新搜索结果:', filters);
        
        // 更新地图显示
        this.updateMapDisplay(filters);
        
        // 更新统计数据
        this.updateStatistics(filters);
        
        // 更新图表
        this.updateCharts(filters);
    }

    /**
     * 重置筛选条件
     */
    resetFilters() {
        console.log('重置筛选条件...');
        
        // 重置表单
        document.querySelectorAll('select, input').forEach(element => {
            if (element.type !== 'hidden') {
                element.value = element.defaultValue || '';
            }
        });
        
        // 重新加载默认数据
        this.loadGeoData();
        this.loadStatistics();
        this.initCharts();
        
        this.showNotification('已重置筛选条件', 'info');
    }

    /**
     * 更新分析显示
     */
    updateAnalysisDisplay() {
        console.log('更新分析模式显示:', this.analysisMode);
        
        switch (this.analysisMode) {
            case 'heatmap':
                this.showHeatmap();
                break;
            case 'clustering':
                this.showClustering();
                break;
            case 'density':
                this.showDensity();
                break;
            case 'trend':
                this.showTrend();
                break;
        }
    }

    /**
     * 显示热力图
     */
    showHeatmap() {
        console.log('显示热力图模式');
        this.showNotification('切换到热力图模式', 'info');
    }

    /**
     * 显示聚类分析
     */
    showClustering() {
        console.log('显示聚类分析模式');
        this.showNotification('切换到聚类分析模式', 'info');
    }

    /**
     * 显示密度分析
     */
    showDensity() {
        console.log('显示密度分析模式');
        this.showNotification('切换到密度分析模式', 'info');
    }

    /**
     * 显示趋势分析
     */
    showTrend() {
        console.log('显示趋势分析模式');
        this.showNotification('切换到趋势分析模式', 'info');
    }

    /**
     * 更新地图显示
     */
    updateMapDisplay(filters) {
        console.log('更新地图显示:', filters);
        // 根据筛选条件更新地图
    }

    /**
     * 更新统计数据
     */
    updateStatistics(filters) {
        console.log('更新统计数据:', filters);
        // 根据筛选条件更新统计
    }

    /**
     * 更新图表
     */
    updateCharts(filters) {
        console.log('更新图表:', filters);
        // 根据筛选条件更新图表
    }

    /**
     * 显示图层控制
     */
    showLayerControl() {
        console.log('显示图层控制');
        this.showNotification('图层控制功能开发中...', 'info');
    }

    /**
     * 切换全屏
     */
    toggleFullscreen() {
        const mapContainer = document.getElementById('map');
        if (mapContainer) {
            if (!document.fullscreenElement) {
                mapContainer.requestFullscreen();
            } else {
                document.exitFullscreen();
            }
        }
    }

    /**
     * 处理图表点击
     */
    handleChartClick(event, chartType) {
        console.log('图表点击:', chartType, event);
        
        if (chartType === 'pollution') {
            this.showNotification('查看污染类型详情', 'info');
        } else if (chartType === 'trend') {
            this.showNotification('查看时间趋势详情', 'info');
        }
    }

    /**
     * 导出地理数据
     */
    exportGeoData() {
        console.log('导出地理数据...');
        
        this.showNotification('正在导出地理数据...', 'info');
        
        setTimeout(() => {
            this.showNotification('地理数据导出成功！', 'success');
        }, 1500);
    }

    /**
     * 显示通知消息
     */
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 ${
            type === 'success' ? 'bg-green-500 text-white' : 
            type === 'error' ? 'bg-red-500 text-white' : 
            'bg-blue-500 text-white'
        }`;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        // 3秒后自动移除
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }

    /**
     * 获取地理编码
     */
    async geocodeAddress(address) {
        console.log('地理编码:', address);
        
        try {
            // 模拟地理编码API调用
            await new Promise(resolve => setTimeout(resolve, 500));
            
            return {
                lat: 22.5431 + Math.random() * 0.1,
                lng: 114.0579 + Math.random() * 0.1,
                address: address
            };
        } catch (error) {
            console.error('地理编码失败:', error);
            return null;
        }
    }

    /**
     * 计算距离
     */
    calculateDistance(lat1, lng1, lat2, lng2) {
        const R = 6371; // 地球半径（公里）
        const dLat = this.toRadians(lat2 - lat1);
        const dLng = this.toRadians(lng2 - lng1);
        
        const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                  Math.cos(this.toRadians(lat1)) * Math.cos(this.toRadians(lat2)) *
                  Math.sin(dLng/2) * Math.sin(dLng/2);
        
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        return R * c;
    }

    /**
     * 角度转弧度
     */
    toRadians(degrees) {
        return degrees * (Math.PI / 180);
    }

    /**
     * 分析热点区域
     */
    analyzeHotspots(data) {
        console.log('分析热点区域:', data);
        
        // 使用DBSCAN或其他聚类算法
        const hotspots = this.performClustering(data);
        
        return hotspots;
    }

    /**
     * 执行聚类分析
     */
    performClustering(data) {
        // 简化的聚类算法
        const clusters = [];
        const visited = new Set();
        
        data.forEach((point, index) => {
            if (visited.has(index)) return;
            
            const cluster = [point];
            visited.add(index);
            
            // 查找邻近点
            data.forEach((otherPoint, otherIndex) => {
                if (visited.has(otherIndex)) return;
                
                const distance = this.calculateDistance(
                    point.lat, point.lng,
                    otherPoint.lat, otherPoint.lng
                );
                
                if (distance < 0.5) { // 500米内
                    cluster.push(otherPoint);
                    visited.add(otherIndex);
                }
            });
            
            if (cluster.length > 1) {
                clusters.push(cluster);
            }
        });
        
        return clusters;
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 初始化经纬度分析管理器
    window.coordinateAnalysisManager = new CoordinateAnalysisManager();
    
    // 绑定全局函数
    window.showLocationDetail = (location) => {
        window.coordinateAnalysisManager.showLocationDetail(location);
    };
    
    // 绑定表格查看按钮
    document.querySelectorAll('button:has(.fa-eye)').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const row = e.target.closest('tr');
            const location = row.querySelector('.font-medium').textContent;
            window.coordinateAnalysisManager.showLocationDetail(location);
        });
    });
    
    // 绑定地图缩放按钮
    document.addEventListener('click', (e) => {
        if (e.target.closest('.fa-plus')) {
            console.log('放大地图');
        } else if (e.target.closest('.fa-minus')) {
            console.log('缩小地图');
        } else if (e.target.closest('.fa-home')) {
            console.log('重置地图视图');
        }
    });
});